//
//  UIView+CYExtension.m
//  DDSocial
//
//  Created by 阿帕 on 2018/7/6.
//  Copyright © 2018年 XY. All rights reserved.
//

#import "UIView+CYExtension.h"

@implementation UIView (CYExtension)

- (CGFloat)cy_x
{
    return self.frame.origin.x;
}
- (void)setCy_x:(CGFloat)cy_x
{
    CGRect cyFrame = self.frame;
    cyFrame.origin.x = cy_x;
    self.frame = cyFrame;
}

-(CGFloat)cy_y
{
    return self.frame.origin.y;
}
-(void)setCy_y:(CGFloat)cy_y
{
    CGRect cyFrame = self.frame;
    cyFrame.origin.y = cy_y;
    self.frame = cyFrame;
}

-(CGPoint)cy_origin
{
    return self.frame.origin;
}
-(void)setCy_origin:(CGPoint)cy_origin
{
    CGRect cyFrame = self.frame;
    cyFrame.origin = cy_origin;
    self.frame = cyFrame;
}

-(CGFloat)cy_width
{
    return self.frame.size.width;
}
-(void)setCy_width:(CGFloat)cy_width
{
    CGRect cyFrame = self.frame;
    cyFrame.size.width = cy_width;
    self.frame = cyFrame;
}

-(CGFloat)cy_height
{
    return self.frame.size.height;
}
-(void)setCy_height:(CGFloat)cy_height
{
    CGRect cyFrame = self.frame;
    cyFrame.size.height = cy_height;
    self.frame = cyFrame;
}

-(CGSize)cy_size
{
    return self.frame.size;
}
- (void)setCy_size:(CGSize)cy_size
{
    CGRect cyFrame = self.frame;
    cyFrame.size = cy_size;
    self.frame = cyFrame;
}

-(CGFloat)cy_centerX{
    
    return self.center.x;
}

-(void)setCy_centerX:(CGFloat)cy_centerX{
    
    CGPoint cyFrmae = self.center;
    cyFrmae.x = cy_centerX;
    self.center = cyFrmae;
}

-(CGFloat)cy_centerY{
    
    return self.center.y;
}

-(void)setCy_centerY:(CGFloat)cy_centerY{
    
    CGPoint cyFrame = self.center;
    cyFrame.y = cy_centerY;
    self.center = cyFrame;
}

- (CGFloat)cy_right{
    
    return CGRectGetMaxX(self.frame);
}

- (CGFloat)cy_bottom{
    
    return CGRectGetMaxY(self.frame);
}

- (void)setCy_right:(CGFloat)cy_right{
    
    self.cy_x = cy_right - self.cy_width;
}

- (void)setCy_bottom:(CGFloat)cy_bottom{
    
    self.cy_y = cy_bottom - self.cy_height;
}

- (BOOL)intersectWithView:(UIView *)view{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect selfRect = [self convertRect:self.bounds toView:window];
    CGRect viewRect = [view convertRect:view.bounds toView:window];
    return CGRectIntersectsRect(selfRect, viewRect);
}

- (BOOL)isShowingOnKeyWindow {
    // 主窗口
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    // 以主窗口左上角为坐标原点, 计算self的矩形框
    CGRect newFrame = [keyWindow convertRect:self.frame fromView:self.superview];
    CGRect winBounds = keyWindow.bounds;
    
    // 主窗口的bounds 和 self的矩形框 是否有重叠
    BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);
    
    return !self.isHidden && self.alpha > 0.01 && self.window == keyWindow && intersects;
}

+(instancetype)cy_viewFromXib
{
    return [[NSBundle mainBundle]loadNibNamed:NSStringFromClass(self) owner:nil options:nil].firstObject;
}


@end
